/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Google Code Wiki Viewer.
 *
 * The Initial Developer of the Original Code is Atte Kemppilä.
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 * Atte Kemppilä <atte.kemppila@iki.fi>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */


const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");

Cu.import("resource://GoogleCodeWikiViewer/common.jsm");


function GoogleCodeWikiStreamConverter()
{
    // empty
}

GoogleCodeWikiStreamConverter.prototype =
{
    classID: Components.ID("{7f86d324-7591-11e0-b55c-20cf30ccb8fb}"),
    contractID: "@mozilla.org/streamconv;1?from=" + GCW_MIME + "&to=*/*",
    classDescription: "Google Code Wiki to HTML stream converter",
    
    QueryInterface:
        XPCOMUtils.generateQI([
            Ci.nsIRequestObserver,
            Ci.nsIStreamConverter,
            Ci.nsIStreamListener,
        ]),
    
    // nsIStreamConverter
    
    asyncConvertData: function(sourceType, targetType, listener, context)
    {
        this.listener = listener;
    },
    
    convert: function(inputStream, sourceType, targetType, context)
    {
        throw Cr.NS_ERROR_NOT_IMPLEMENTED;
    },
    
    // nsIRequestObserver
    
    onStartRequest: function(request, context)
    {
        // input is read into |data| in onDataAvailable() and converted in onStopRequest()
        this.data = "";
        
        this.channel = request.QueryInterface(Ci.nsIChannel);
        this.charset = this.channel.contentCharset || "UTF-8";
        
        // input is converted to html
        this.channel.contentType = "text/html";
        this.channel.contentCharset = "UTF-8";
        
        this.listener.onStartRequest(this.channel, context);
    },
    
    onStopRequest: function(request, context, statusCode)
    {
        try
        {
            let text = this.data;
            let args = {title: this.channel.URI.spec};
            let self = this;
            
            this._convert(text, args, function(html) { self._onStopRequest(request, context, statusCode, html); });
        }
        catch (e)
        {
            this._onStopRequest(request, context, statusCode, e);
            Cu.reportError(e);
        }
    },
    
    _onStopRequest: function(request, context, statusCode, html)
    {
        // convert string to utf-8 stream
        let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
        converter.charset = "UTF-8";
        let is = converter.convertToInputStream(html);
        
        this.listener.onDataAvailable(this.channel, context, is, 0, is.available());
        this.listener.onStopRequest(this.channel, context, 200);
        
        this.listener = null;
        this.channel = null;
        this.charset = null;
    },
    
    // nsIStreamListener
    
    onDataAvailable: function(request, context, inputStream, offset, count)
    {
        let cis = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream);
        cis.init(inputStream, this.charset, -1, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
        
        let str = {};
        while (cis.readString(4096, str) != 0)
            this.data += str.value;
    },
    
    // private methods
    
    _convert: function(text, args, callback)
    {
        Cu.import("resource://GoogleCodeWikiViewer/GoogleCodeWikiParser.jsm");
        
        let parser = new GoogleCodeWikiParser();
        parser.parse(text, args, callback);
    },
}


const NSGetFactory = XPCOMUtils.generateNSGetFactory([GoogleCodeWikiStreamConverter]);
